package com.yanxi.exception;

import com.yanxi.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler
    public Result handleException(Exception ex){
        log.error("异常信息：",ex);
        return Result.error("对不起，操作失败，请联系管理员");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException ex){
        log.error("DuplicateKeyException异常信息：",ex);
        String msg = ex.getMessage();
        //截取Duplicate entry之后的信息
        msg = msg.substring(msg.indexOf("Duplicate entry")).split(" ")[2];
        return Result.error(msg+"已存在");
    }

}
